<script setup lang="ts">
import { getList } from '@/api/system/menu';
import { getMenuIdsByRoleId, saveRoleMenu } from '@/api/system/role'
import { ref, reactive, toRefs} from 'vue';
import { notify } from '@/utils/element';

const treeRef = ref();

const state = reactive({
    loading: false,
    visible: false,
    role: {} as SysRoleType,
    menuList: [] as SysMenuType[],
    menuIds: [] as string[],
    checked: false,
    expandAll: false,
    submitting: false,
});

const { loading, visible, role, menuList, menuIds, checked, expandAll, submitting } = {...toRefs(state)};

defineExpose({
    open,
});
//打开窗口
async function open(role: SysRoleType) {
  console.log('role',role)
    state.role = role;
    state.visible = true;
    await loadMenuList();
    //查询角色拥有的ids
    await loadRoleMenuIds();
    await checkOldMenuNode();
}

function close() {
    if(state.submitting) return;
    state.menuIds = [];
    state.menuList = [];
    state.checked = false;
    state.expandAll = false;
    state.visible = false;
}

//查询所有菜单项
async function loadMenuList() {
    try {
        state.loading = true;
        let paramData:SysMenuQuery = {keyword:''};
        const { data } = await getList(paramData);
        state.menuList = data;
    } catch (error) {
    } finally {
        state.loading = false;
    }
}

async function loadRoleMenuIds() {
    try {
        state.loading = true;
        const { data } = await getMenuIdsByRoleId(state.role.roleId)
        state.menuIds = data;
    } catch (error) {
    } finally {
        state.loading = false;
    }
}

//回显角色原有的权限菜单
function checkOldMenuNode() {
    const { menuIds } = state;
    menuIds.forEach(id => {
        //获取节点对象
        const node = treeRef.value.getNode(id);
        if(node && node.isLeaf) treeRef.value.setChecked(id, true);
    });
}

function handleCheckAll() {
    state.checked = !state.checked;
    if(state.checked) treeRef.value.setCheckedNodes(state.menuList);
    else treeRef.value.setCheckedNodes([]);
}

function handleExpand() {
    state.expandAll = !state.expandAll;
    changeTreeNodeStatus(treeRef.value.store.root);
}

//function changeTreeNodeStatus(node: Node) {
function changeTreeNodeStatus(node: any) {
    //console.log('node',node)
    node.expanded = state.expandAll;
    for(let i=0; i < node.childNodes.length; i++) {
        node.childNodes[i].expanded = state.expandAll;
        if(node.childNodes[i].childNodes.length > 0) {
            changeTreeNodeStatus(node.childNodes[i]);
        }
    }
}

async function submitForm() {
    try {
        state.submitting = true;
        const checkedMenuIds = treeRef.value.getCheckedKeys();
        //console.log('checkedMenuIds',checkedMenuIds)
        const parentIds = treeRef.value.getHalfCheckedKeys();
        //console.log('parentIds',parentIds)
        const menuIds = parentIds.concat(checkedMenuIds);
        await saveRoleMenu(state.role.roleId, menuIds);
        notify('分配权限成功！', {type: 'success'});
        state.submitting = false;
        close();
    } catch (error) {
    } finally {
        state.submitting = false;
    }
}
</script>

<template>
    <el-drawer :title="`分配【${role.roleName}】权限`"  v-model="visible" :before-close="close" direction="rtl" size="400px">
        <div v-loading="loading">
            <el-tree
                ref="treeRef"
                :data="menuList"
                node-key="menuId"
                show-checkbox
                highlight-current
                :props="{children: 'children',}"
                :default-expand-all="expandAll"
            >
                <template #default="{node, data}">
                    <span class="custom-tree-node">
                        <!--一二级菜单类型显示自定义图标-->
                        <SvgIcon v-if="[1,2].includes(node.level)" :name="data.icon"/>
                        <!--三四级菜单显示'菜单'或'按钮'图标-->
                        <el-icon v-else>
                            <ele-Menu v-if="data.menuType == 'C'"/>
                            <ele-SwitchButton v-else-if="data.menuType == 'F'"/>
                        </el-icon>
                        <span class="ml10">{{ data.menuName }}</span>
                    </span>
                </template>
            </el-tree>
        </div>
        <template #footer>
            <el-button :loading="submitting" @click="submitForm" type="primary">提交</el-button>
            <el-button @click="handleCheckAll">全选/不选</el-button>
            <el-button @click="handleExpand">展开/收起</el-button>
            <el-button @click="close">取消</el-button>
        </template>
    </el-drawer>
</template>

<style lang="scss" scoped>
.custom-tree-node {
    font-size: 14px;
    display: flex;
    align-items: center;
    padding-left: 10px;
}
</style>
